using System;
using System.Collections.Specialized;
using System.Data;
using System.Text;
using BlogEngine.Core;

namespace BlogEngine.Core.Providers
{
  /// <summary>
  /// Microsoft SQL Server Implementation of BlogProvider
  /// </summary>
  public partial class MSSQLBlogProvider : BlogProviderBase
  {
    /// <summary>
    /// Loads the settings from the provider.
    /// </summary>
    /// <returns></returns>
    public override StringDictionary LoadSettings()
    {
        StringDictionary dic = new StringDictionary();

        SQLManagedConnection myConn = SQLManagedConnection.GetConnection(_DatabaseName);

        try
        {
            myConn.GetTextCommand("SELECT SettingName, SettingValue FROM be_Settings");

            using (IDataReader rdr = myConn.ExecuteReader())
            {
                while (rdr.Read())
                    dic.Add(rdr.GetString(0), rdr.GetString(1));

                rdr.Close();
            }
        }
        finally
        {
            myConn.CloseIfNonTransactional();
        }

        return dic;
    }

    /// <summary>
    /// Saves the settings to the provider.
    /// </summary>
    /// <param name="settings"></param>
    public override void SaveSettings(StringDictionary settings)
    {
        if (settings == null)
            throw new ArgumentNullException("settings");

        SQLManagedConnection myConn = SQLManagedConnection.GetConnectionForTransaction(_DatabaseName);

        try
        {
            myConn.GetTextCommand("DELETE FROM be_Settings");
            myConn.ExecuteNonQuery();

            foreach (string key in settings.Keys)
            {
                myConn.GetTextCommand("INSERT INTO be_Settings (SettingName, SettingValue) VALUES (@name, @value)");
                myConn.AddInParameter("@name", DbType.String, key);
                myConn.AddInParameter("@value", DbType.String, settings[key]);
                myConn.ExecuteNonQuery();
            }

            myConn.Commit();
        }
        finally
        {
            //if commit worked then this will do nothing
            myConn.Rollback();
        }
    }
  }
}
